//Scripts for the RFL home page

"use strict";

$(document).ready(function(){
	//Scripts which are run right after the page is done loading
	//Uses jQuery's famouse document ready function.
	var c, ncols;
	
	//Enable tablesorter to sort numbers with commas in them.
	//From: http://lab.christianmontoya.com/jquery-tablesort-numbers-commas/
	jQuery.tablesorter.addParser({
		id: "commaDigit",
		is: function(s, table) {
			c = table.config;
			return jQuery.tablesorter.isDigit(s.replace(/,/g, ""), c);
		},
		format: function(s) {
			return jQuery.tablesorter.formatFloat(s.replace(/,/g, ""));
		},
		type: "numeric"
	});
	
	//Make the table sortable
	//The columns are different if the user is "staff"
	//For staff, there will be more than 7 columns.
	
	//Only do it if the table exists
	//(It won't be there for non-logged in users, or users with 0 gardens.)
	if ($("#garden_table").length > 0){
		//count the number of columns:
		ncols = $("#garden_table").find("tr")[0].cells.length;
		if (ncols > 7){
			//Staff view
			$("#garden_table").tablesorter({
				headers:{
					5: {sorter: "commaDigit"},
					6: {sorter: "commaDigit"},
					7: {sorter: "commaDigit"},
					8: {sorter: "commaDigit"},
					9: {sorter:false}
				}
			});
		} else {
			//Regular user view
			$("#garden_table").tablesorter({
				headers:{
					2: {sorter: "commaDigit"},
					3: {sorter: "commaDigit"},
					4: {sorter: "commaDigit"},
					5: {sorter: "commaDigit"},
					6: {sorter:false}
				}
			});
		}
	}
	//Launch Garden Button
	//$(".launch_garden").button({ icons: {primary:"ui-icon-pencil"} });
	$(".new_garden"   ).button({ icons: {primary:"ui-icon-plusthick"} });
	
	$(".launch_garden").click(launch_garden);
	$(".new_garden"   ).click(launch_garden);
	
	//Delete Garden Link
	//$(".delete_garden").button({ icons: {primary:"ui-icon-close"}, text: false});
	$(".delete_garden").click(function(){
		var garden_id, garden_name;
		garden_id = $(this).attr("title");
		$("#delete_id").val(garden_id);
		garden_name = $(this).find(".garden_name").text();
		//launch a popup dialog to confirm the user really wants to delete.
		//actual delete code will be launched from the "Yes" button there
		$("#garden_name").html(garden_name);
		$("#delete_dialog").dialog("open");
	});
	
	//Duplicate Garden Link (all it does is launch the Duplicate Dialog box)
	$("#duplicate_link").click(function(){
		//make the first option in the dialog box selected.
		var first_val = $("#duplicate option:first").val();
		$("#duplicate").val(first_val);
		
		//get the name of the selected garden
		//var garden_name = $("#duplicate option:selected").text();
		
		//Finally, open the dialog box
		$("#duplicate_dialog").dialog("open");
		return false;
	});
	
	$("#register_button").button();
	$("#login_button").button();
	
	
	//Duplicate Garden Dialog
	$("#duplicate_dialog").dialog({
		autoOpen: false,
		modal: true,
		width: 400,
		height: 350,
		position: "center",
		buttons: {
			"Duplicate": duplicate_garden,
			"Cancel": function(){
				$(this).dialog("close");
			}
		}
	});

	//Delete confirmation dialog
	$("#delete_dialog").dialog({
		autoOpen:false,
		model: true,
		width: 300,
		heigh: 250,
		position: "center",
		buttons: {
			"Delete": delete_garden,
			"Cancel": function(){
				$(this).dialog("close");
			}
		}
	});
	
	// HELP Dialog Box 
	$("#helpdialog").dialog({
		autoOpen: false,
		width: 500,
		height:400,
		modal: true,
		position: "center",
		buttons: {"Close": function(){
			$(this).dialog("close"); 
			}
		}
	});
	
	//Create the MORE INFO buttons using rollover effects
	$(".moreinfo").mouseenter(function(){
		$(this).attr("src", "/site_media/images/info_mouseover.gif");
	});
	
	$(".moreinfo").mousedown(function(){
		$(this).attr("src", "/site_media/images/info_mousedown.gif");
	});
	
	$(".moreinfo").mouseup(function(){
		$(this).attr("src", "/site_media/images/info_mouseover.gif");
	});
	
	$(".moreinfo").mouseout(function(){
		$(this).attr("src", "/site_media/images/info.gif");
	});
	
	$(".moreinfo").each(function(i) {
		//$(this).button({ icons: {primary:"ui-icon-info"}, text: false });   //OLD
		$(this).click(function() {
			//put the right contents in the dialog box.
			//The help button icon image has two classes, e.g. class="moreinfo help_zip"
			//We need to extract the second one. I wish I figured this out myself: http://stackoverflow.com/questions/2887976/get-other-classes-from-an-element-with-jquery
			var helpID, helpHtml;
			helpID = $(this).attr("class").replace(/\s+/,' ').split(' ')[1];
			helpHtml = $("#" + helpID).html();
			$("#helpinfo").html(helpHtml);
			$("#helpdialog").dialog("open");
			//Scroll to the top of the help dialog (because the user may have previously opened it, scrolled down, then closed)
			$('#helpdialog').scrollTop(0);
			return false;
		});
	});
	
});

function delete_garden(){
//Function that is called when the user clicks the delete button
//AND then clicks OK on the confirmation popup box.
	var garden_id = $("#delete_id").val();
	$.ajax({
		type: "POST",
		url: "../deleter/",
		data: {"garden_id": garden_id},
		success: function(obj){
			if (obj.deleted === true){
				//remove the entire row from the table
				$(".launch_garden[title='" + garden_id +"']").parent().parent().remove();
				//Need to update tablesorter's cache so the row doesn't re-appear when the user sorts (simple one-line command)
				$("#garden_table").trigger("update");
				//Close the dialog box.
				$("#delete_dialog").dialog("close");
			} else {
				alert("Unable to delete your data.");
				$("#delete_dialog").dialog("close");
			}
		}
	});
}

function duplicate_garden(){
	//Function that is called when the user clicks the "Duplicate existing landscape..." button
	//It sets up and launches the Duplicate Landscape dialog box.
	var garden_id, garden_name;
	//ID of the garden that will be duplicated
	garden_id = $("#duplicate option:selected").val();
	
	//Name for the new garden
	garden_name = $("#duplicate_name").val();
	
	//series of steps that need to happen:
	//.1. Send this information to the server, where a script will do all the necessary duplicating, adding a new garden to the database.
	// 2. Reload this page (I think that's the easiest way, rather than monkeying around with adding rows to the table, etc... would require so many lines of code. 
	$.ajax({
		type: "POST",
		url: "../duplicater/",
		data: {"garden_id": garden_id, "garden_name": garden_name},
		success: function(obj){
			if(obj.duplicated !== false){
				alert("Your landscape was cloned! Click OK to continue.");
				location.reload();
			} else {
				alert("Unable to duplicate landscape.");
				
			}
		}
	});
}

function launch_garden(){
	//Function that is called when the user clicks on a Launch Garden button
	//It puts the ID of the garden the user wants to edit into a hidden form field,
	//and then submits that form
	var garden_id = $(this).attr("title");
	$("#garden_id").val(garden_id);
	$("#load_form").submit();
}

$(document).ajaxSend(function(event, xhr, settings) {
	//Extra method to bind to jQuery's Ajax function
	// see: https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax
	// and http://api.jquery.com/ajaxSend/
	
	function getCookie(name) {
		var cookies, cookie, cookieValue = null, i;
		if (document.cookie && document.cookie != '') {
			cookies = document.cookie.split(';');
			for (i = 0; i < cookies.length; i++) {
				cookie = jQuery.trim(cookies[i]);
				// Does this cookie string begin with the name we want?
				if (cookie.substring(0, name.length + 1) === (name + '=')) {
					cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
					break;
				}
			}
		}
		return cookieValue;
	}
	function sameOrigin(url) {
		// url could be relative or scheme relative or absolute
		var host = document.location.host, // host + port
		protocol = document.location.protocol,
		sr_origin = '//' + host,
		origin = protocol + sr_origin;
		
		// Allow absolute or scheme relative URLs to same origin
		return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
			(url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
			// or any other URL that isn't scheme relative or absolute i.e relative.
			!(/^(\/\/|http:|https:).*/.test(url));
	}
	function safeMethod(method) {
		return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
	}
	
	if (!safeMethod(settings.type) && sameOrigin(settings.url)) {
		xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
	}
});

